import { reactive } from 'vue'
import type { ItemStateInterface } from './models'
import type { ItemInterface } from '@/models/items'

// the items module state
const itemState = reactive<ItemStateInterface>({
  loading: false,
  items: [],
})

// the items store actions implementation
const actions = {
  loadItems: async () => {
    itemState.loading = true
    itemState.items = []

    // mock some data
    let mockData: ItemInterface[] = [
      { id: 1, name: 'Item 1', selected: false },
      { id: 2, name: 'Item 2', selected: false },
      { id: 3, name: 'Item 3', selected: false },
      { id: 4, name: 'Item 4', selected: false },
      { id: 5, name: 'Item 5', selected: false },
    ]

    setTimeout(() => {
      itemState.items = mockData
      itemState.loading = false
    }, 1000)
  },

  toggleItemSelected: async (id: number) => {
    const item = (itemState.items || []).find((item) => item.id === id)
    if (item) {
      item.selected = !item.selected
    }
  },
}

// the items store getters implementation
// these will be consumed by the components
const getters = {
  get loading() {
    return itemState.loading
  },
  get items() {
    return itemState.items
  },
}

export interface ItemsStoreInterface {
  actions: typeof actions
  getters: typeof getters
}

// hook that we will use in the components
export function useItemsStore(): ItemsStoreInterface {
  return {
    getters,
    actions,
  }
}
